﻿
namespace MyFurion.Application.Controller
{
    /// <summary>
    /// 用户
    /// </summary>
    public class UserController:IDynamicApiController
    {
        private readonly UserRepository _repository;
        private readonly UserRoleRepository _userRoleRepository;
        public UserController(UserRepository userRepository,UserRoleRepository userRoleRepository)
        {
            _repository = userRepository;
            _userRoleRepository= userRoleRepository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("add")]
        [ActionPermission("userAdd")]
        public async Task Add(UserInfoAdd input)
        {
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined,"状态"));
            }
            bool isExists = await _repository.DataExists(input.Account);
            if (isExists)
            {
                throw Oops.Oh(ErrorMsgConst.AccountExist);
            }
            var model = input.Adapt<UserInfo>();
            model.LoginPwd= MD5Encryption.Encrypt(input.LoginPwd);
            bool result=await _repository.Add(model);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.SaveError);
            }
            else
            {
                //用户角色关联信息
                await _userRoleRepository.GrantRole(model.Id,input.RoleIds);
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        [ActionPermission("userEdit")]
        public async Task Update(UserInfoUpdate input)
        {
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "状态"));
            }
            bool isExists = await _repository.DataExists(input.Account,input.Id);
            if (isExists)
            {
                throw Oops.Oh(ErrorMsgConst.AccountExist);
            }
            var model = await _repository.GetEntityById(input.Id);
            if (model == null)
            {
                throw Oops.Oh(ErrorMsgConst.NoRecord);
            }
            model.UserName = input.UserName;
            model.NickName= input.NickName;
            model.Account = input.Account;
            model.Tel=input.Tel;
            model.Email = input.Email;
            model.Status= input.Status;
            model.OrgId= input.OrgId;
            bool result = await _repository.Update(model);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.SaveError);
            }
            else
            {
                //用户角色关联信息
                await _userRoleRepository.GrantRole(model.Id, input.RoleIds);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpDelete("delete")]
        [ActionPermission("userDel")]
        public async Task Delete([FromQuery]BaseIdInput input)
        {
            bool result = await _repository.DeleteById(input.Id);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.DeleteError);
            }
            else
            {
                //删除用户角色关联信息
                await _userRoleRepository.DeleteByWhere(it=>it.UserId == input.Id);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpDelete("batchDelete")]
        public async Task BatchDelete([FromQuery]BaseIdsInput input)
        {
            bool result = await _repository.DeleteByWhere(it=>input.Ids.Contains(it.Id));
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.DeleteError);
            }
            else
            {
                //删除用户角色关联信息
                await _userRoleRepository.DeleteByWhere(it =>input.Ids.Contains(it.UserId));
            }
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("setStatus")]
        public async Task ModifyStatus(SetStatusInfo input)
        {
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "状态"));
            }
            bool result = await _repository.Update(it => it.Id == input.Id, it => new UserInfo() { Status = input.Status });
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.StatusError);
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("modifyPwd")]
        public async Task ModifyPassword(ModifyPasswordInput input)
        {
            var model = await _repository.GetEntityById(input.Id);
            if (model == null)
            {
                throw Oops.Oh(ErrorMsgConst.NoRecord);
            }
            string oldMd5 = MD5Encryption.Encrypt(input.OldPassword);
            if (string.Compare(oldMd5, model.LoginPwd, true) != 0)
            {
                throw Oops.Oh("旧密码输入错误");
            }
            string newMd5 = MD5Encryption.Encrypt(input.NewPassword);
            bool result = await _repository.Update(it => it.Id == input.Id, it => new UserInfo() { LoginPwd = newMd5 });
            if (!result)
            {
                throw Oops.Oh("密码修改失败");
            }
        }
        /// <summary>
        /// 初始化密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("resetPwd")]
        public async Task ResetPwd(ResetPwdInput input)
        {
            var configInfo = await App.GetService<ConfigRepository>().GetFirstAsync(it => it.ConfigCode == "DefaultPwd");
            string defaultPwd = configInfo?.ConfigValue;
            string pwdMd5 = MD5Encryption.Encrypt(defaultPwd);
            bool result = await _repository.Update(it => it.Id == input.Id, it => new UserInfo() { LoginPwd = pwdMd5 });
            if (!result)
            {
                throw Oops.Oh("初始化密码失败");
            }
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("page")]
        public async Task<PageResult<UserInfo>>QueryPage(UserInfoPage input)
        {
            return await _repository.GetPageList(input);
        }
        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<List<UserInfo>> QueryList(UserInfoPage input)
        {
            return await _repository.GetDataList(input);
        }
        /// <summary>
        /// 根据id获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<UserInfo> GetDetail(long id)
        {
            var model = await _repository.GetDetail(id);
            if (model != null)
            {
                model.RoleIds = await _userRoleRepository.GetUserRoleIdList(id);
            }
            return model;
        }            
    }
}
